import { Provide } from '@midwayjs/decorator';
import { InjectEntityModel } from '@midwayjs/orm';
import { Repository, In } from 'typeorm';
import dayjs from 'dayjs';
import { BaseService } from '@core/index';
import { UserEntity } from '@/entity/user';
import { GroupEntity } from '@/entity/group';
import { GroupUserEntity } from '@/entity/groupUser';
import { GroupMsgEntity } from '@/entity/groupMsg';

@Provide()
export class GroupService extends BaseService {
  @InjectEntityModel(GroupEntity)
  groupEntity: Repository<GroupEntity>;

  @InjectEntityModel(GroupUserEntity)
  groupUserEntity: Repository<GroupUserEntity>;

  @InjectEntityModel(GroupMsgEntity)
  groupMsgEntity: Repository<GroupMsgEntity>;

  @InjectEntityModel(UserEntity)
  userEntity: Repository<UserEntity>;

  /**
   * 建群
   */
  async createGroup(name, usersId) {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = userToken.payload.userId;
    // console.log('消息', msgResult);
    const groupNumber = String(dayjs().unix()).slice(1, 10);
    const params = {
      userId: userId, // 创建群人用户id
      name: name, // 群名称
      groupNumber: Number(groupNumber), // 群号随机生成
      imgUrl: 'http://127.0.0.1:7001/public/images/ddd.png', // 群头像
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss'), // 群创建时间
    };
    const result = await this.groupEntity.save(params);
    if (result && result.id) {
      const options = usersId.split(',').map((item: any) => {
        return {
          groupId: result.id,
          userId: item,
        };
      });
      this.groupUserEntity
        .createQueryBuilder()
        .insert()
        .values([{ groupId: result.id, userId: userId }, ...options])
        .execute();
    }

    console.log('params', params);
    return this.success(200, '创建群成功', result);
  }
  /**
   * 加入群聊
   */
  async joinGroup(groupId: number, usersId: string) {
    const options = usersId.split(',').map((item: any) => {
      return {
        groupId: groupId,
        userId: item,
      };
    });
    this.groupUserEntity
      .createQueryBuilder()
      .insert()
      .values([...options])
      .execute();
    return this.success(200, '加入群聊成功');
  }
  /**
   * 获取群列表
   */
  async getGroupList() {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = Number(userToken.payload.userId);
    const result = await this.groupUserEntity.find({
      where: { userId: userId },
    });
    const arrData: any = [];
    result.forEach(item => {
      arrData.push(item.groupId);
    });
    const results = await this.groupEntity.find({
      where: {
        id: In(arrData),
      },
    });
    const formatData = results.map((item: any) => {
      item.type = 2;
      if (item.userId === userId) {
        item.type = 1;
      }
      return item;
    });
    console.log('获取群列表', formatData);
    return this.success(200, '获取群列表', formatData);
  }

  /**
   * 获取群详情
   */
  async getGroupDetails(id: number) {
    const result = await this.groupEntity.findOne({
      where: { id: id },
    });
    return this.success(200, '获取群详情', result);
  }

  /**
   * 修改群信息
   */

  async updateGroup(options) {
    const { groupId, name, imgUrl, note, notice } = options;
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = userToken.payload.userId;
    const groupDetails = await this.groupEntity.findOne({
      where: { id: groupId },
    });
    const result = await this.groupEntity
      .createQueryBuilder()
      .update()
      .set({
        name: name || groupDetails.name, // 群名称
        imgUrl: imgUrl || groupDetails.imgUrl, // 群头像
        note: note || groupDetails.note, // 群备注
        notice: notice || groupDetails.notice, // 群公告
      })
      .where({ userId, id: groupId })
      .execute();
    return this.success(200, '修改群信息', result);
  }

  /**
   * 获取群消息
   */
  async getGroupMsg(groupId: number) {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = userToken.payload.userId;
    const result = await this.groupMsgEntity.find({
      where: {
        groupId: groupId,
      },
      relations: ['users'],
    });
    const formatData = result.map((item: any) => {
      return {
        id: item.id,
        groupId: item.groupId,
        userId: item.userId,
        type: item.userId === userId ? 1 : 2,
        content: item.content,
        status: item.status,
        time: item.time,
        name: item.users.username,
        imgUrl: item.users.imgUrl,
      };
    });
    return this.success(200, '获取群消息', formatData);
  }

  /**
   * 获取群成员列表
   */
  async getGroupMemberList(id: number) {
    // const userToken: any = await this.tokenUtil.verifyToken();
    // const userId = Number(userToken.payload.userId);
    const result = await this.groupUserEntity.find({
      where: { groupId: id },
      relations: ['users'],
    });
    // console.log('resultss', result);
    const formatData = result.map((item: any) => {
      return {
        id: item.id,
        userId: item.userId,
        name: item.note ? item.note : item.users.username,
        imgUrl: item.users.imgUrl,
      };
    });
    return this.success(200, '获取群成员列表', formatData);
  }

  /**
   * 删除群
   */
  async deleteGroup(groupId: number) {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = Number(userToken.payload.userId);
    console.log(groupId);
    // 查找群成员
    const groupUserResult = await this.groupUserEntity.find({
      where: { groupId: groupId },
    });
    // 遍历 得到 群id 和用户id数组 用户删除对应的群成员
    const options = groupUserResult.map((item: any) => {
      return {
        groupId: groupId,
        userId: item.userId,
      };
    });
    // 删除群成员
    console.log('options', options);
    await this.groupUserEntity
      .createQueryBuilder()
      .delete()
      .where(options)
      .execute();
    // 查询群消息 然后 遍历组装成数组 群id (groupId)
    const groupMsg = await (
      await this.groupMsgEntity.find({
        where: { groupId: groupId },
      })
    ).map((item: any) => item.groupId);
    console.log('groupMsg', groupMsg);
    // 删除群消息 判断群消息是否存在 存在就删除掉
    if (groupMsg && groupMsg.length > 0) {
      await this.groupMsgEntity
        .createQueryBuilder()
        .delete()
        .where({ groupId: groupId })
        .execute();
    }
    // 删除群 最后删除群
    await this.groupEntity
      .createQueryBuilder()
      .delete()
      .where({ id: groupId, userId: userId })
      .execute();

    return this.success(200, '删除群成功');
  }

  /**
   * 退出群聊
   */
  async outGroup(groupId: number) {
    const userToken: any = await this.tokenUtil.verifyToken();
    const userId = Number(userToken.payload.userId);
    this.groupUserEntity
      .createQueryBuilder()
      .delete()
      .where({
        groupId: groupId,
        userId: userId,
      })
      .execute();
    return this.success(200, '退出群');
  }
}
